package com.xphu.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author xphu
 * @version 1.0
 * @date 2021/11/11 20:10
 */
public class BIOServer {
    public static void main(String[] args) {
        // 线程机制
        // 思路
        // 1.创建线程池
        // 核心线程数
        int corePoolSize = 3;
        // 最大线程数
        int maxPoolSize = 10;
        //超过 corePoolSize 线程数量的线程最大空闲时间 2秒
        long keepAliveTime = 2;
        // 创建工作队列用于存放提交的等待执行任务
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(3);
        ExecutorService threadPoolExecutor = null;
        try {
            threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
                    maxPoolSize,
                    keepAliveTime,
                    TimeUnit.SECONDS,
                    workQueue,
                    new ThreadPoolExecutor.AbortPolicy());
            // 2.创建ServerSocket
            ServerSocket serverSocket = new ServerSocket(6666);
            System.out.println("主线程线程:"+Thread.currentThread().getId()+"-"+Thread.currentThread().getName()+"服务器启动了。。。");
            // 循环监听等待客户端连接
            System.out.println("等待客户端连接。。。");
            while (true){
                // 接收客户端的连接
                Socket socket = serverSocket.accept();
                // 3.如果有客户端连接，就创建一个线程与之通信
                threadPoolExecutor.execute(() -> {
                    System.out.println("客户端程线程:"+Thread.currentThread().getId()+"-"+Thread.currentThread().getName()+"创建了连接！");
                    System.out.println("等待客户发送数据");
                    handler(socket);
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 客户端通讯方法
     * @param socket Socket 客户端
     */
    public static void handler(Socket socket){
        byte[] bytes = new byte[1024];
        // 通过socket获取输入流
        try {
            InputStream inputStream = socket.getInputStream();
            // 循环获取客户端的数据
            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    String msg = new String(bytes, 0, read);
                    // 输出客户端发出的信息
                    System.out.println("客户端程线程:"+Thread.currentThread().getId()+"-"+Thread.currentThread().getName()+"接收到客户端发送的数据："+msg);
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            System.out.println("关闭socket和client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
